// import 'dart:async';
// import 'dart:io';

// import 'package:flutter_inapp_purchase/flutter_inapp_purchase.dart';

// class IOSPurchaseManager {
//   static final IOSPurchaseManager _instance = IOSPurchaseManager._internal();
//   factory IOSPurchaseManager() => _instance;
//   IOSPurchaseManager._internal();

//   final FlutterInappPurchase _iap = FlutterInappPurchase.instance;

//   bool _isInitialized = false;
//   StreamSubscription<Purchase>? _purchaseSub;
//   StreamSubscription<PurchaseError>? _errorSub;

//   Function(Purchase)? onPurchaseSuccess;
//   Function(PurchaseError)? onPurchaseError;
//   Function(String)? onPurchaseCancelled;

//   /// 初始化
//   Future<bool> initialize() async {
//     if (_isInitialized) return true;

//     try {
//       await _iap.initConnection;
//       _setupListeners();
//       _isInitialized = true;
//       print("✅ IAP initialized");
//       return true;
//     } catch (e) {
//       print("❌ IAP initialization failed: $e");
//       return false;
//     }
//   }

//   /// 重新初始化
//   Future<bool> reinitialize() async {
//     if (_isInitialized) {
//       await dispose();
//       await Future.delayed(const Duration(milliseconds: 300));
//     }
//     return await initialize();
//   }

//   /// 设置监听器
//   void _setupListeners() {
//     _purchaseSub = _iap.purchaseUpdatedListener.listen(_handlePurchase);
//     _errorSub = _iap.purchaseErrorListener.listen(_handlePurchaseError);
//   }

//   /// 处理购买更新
//   Future<void> _handlePurchase(Purchase purchase) async {
//     if (!Platform.isIOS) return;

//     try {
//       // iOS 直接认为购买成功（后续验证收据）
//       await _validateAndFinish(purchase);
//     } catch (e) {
//       onPurchaseError
//           ?.call(PurchaseError(code: ErrorCode.Unknown, message: e.toString()));
//     }
//   }

//   /// 处理购买错误
//   void _handlePurchaseError(PurchaseError error) {
//     if (error.code == ErrorCode.UserCancelled) {
//       onPurchaseCancelled?.call("User cancelled purchase");
//     } else {
//       onPurchaseError?.call(error);
//     }
//   }

//   /// 购买商品
//   Future<void> purchaseProduct(String productId) async {
//     if (!_isInitialized) throw Exception("IAP not initialized");
//     try {
//       await _iap.requestPurchase(productId);
//     } catch (e) {
//       print("❌ purchaseProduct error: $e");
//       rethrow;
//     }
//   }

//   /// 验证收据 + 完成交易
//   Future<void> _validateAndFinish(Purchase purchase) async {
//     // TODO: 上传 purchase.purchaseToken 到服务器验证
//     bool isValid = true; // 模拟验证结果

//     if (isValid) {
//       await _iap.finishTransaction(purchase, isConsumable: true);
//       onPurchaseSuccess?.call(purchase);
//     } else {
//       onPurchaseError?.call(PurchaseError(
//           code: ErrorCode.Unknown, message: "Receipt validation failed"));
//     }
//   }

//   /// 获取商品信息
//   Future<List<ProductCommon>> getProducts(List<String> productIds) async {
//     if (!_isInitialized) throw Exception("IAP not initialized");
//     return await _iap.fetchProducts<Product>(
//       skus: productIds,
//       type: ProductType.InApp,
//     );
//   }

//   /// 恢复购买
//   Future<List<Purchase>> restorePurchases() async {
//     if (!_isInitialized) throw Exception("IAP not initialized");
//     await _iap.restorePurchases();
//     return await _iap.getAvailablePurchases();
//   }

//   /// 释放资源
//   Future<void> dispose() async {
//     await _purchaseSub?.cancel();
//     await _errorSub?.cancel();
//     try {
//       await _iap.endConnection;
//     } catch (_) {}
//     _isInitialized = false;
//   }
// }
